<template>
  <h2>todolist - {{ formatTimer }} - <button @click="stop">暂停</button></h2>
  <input type="text" v-model="value" />
  <button @click="handleClick">添加</button>
  <ul>
    <li v-for="item in list" :key="item.id">
      {{ item.name }} - <button @click="removeItem(item.id)">删除</button>
    </li>
  </ul>
</template>

<script>
import { ref, computed, onMounted } from "vue";
export default {
  setup() {
    const [list, removeItem] = removeModule();
    const [value, handleClick] = addModule(list);
    const formatTimer = timeModule();

    return {
      value,
      list,
      handleClick,
      removeItem,
      formatTimer,
    };
  },
};

const addModule = (list) => {
  const value = ref("");
  const handleClick = () => {
    list.value.push({
      id: new Date().getTime(),
      name: value.value,
    });
    value.value = "";
  };

  return [value, handleClick];
};

const removeModule = () => {
  // 删除功能
  const list = ref([
    {
      name: "zhangsan",
      id: 1,
    },
    {
      name: "lisi",
      id: 2,
    },
  ]);
  const removeItem = (id) => {
    list.value = list.value.filter((item) => item.id !== id);
  };

  return [list, removeItem];
};

const timeModule = () => {
  const timer = ref(0);

  const formatTimer = computed(() => {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(timer.value);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + s;
  });

  onMounted(() => {
    timer.value = new Date().getTime();
    setInterval(() => {
      timer.value = new Date().getTime();
    }, 1000);
  });

  return formatTimer;
};
</script>
